<?php


namespace App\Service\Api\Wechat;


use App\Dao\CooperativeDao;
use App\Model\Cooperative;
use App\Utils\Log;
use App\Utils\Wechat\OpenPlatform\MiniProgram;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;

class OpenPlatformService
{
    /**
     * @Inject()
     * @var CooperativeDao
     */
    private $cooperativeDao;

    /**
     * @Inject()
     * @var MiniProgram
     */
    private $miniProgram;

    /**
     * @param string $appID
     * @param array $data
     * @return bool
     */
    public function notice(string $appID, array $data)
    {
        switch($data['Event']) {
            case 'weapp_audit_success':
                try {
                    $retryCount = 3;
                    retry:
                    $res = $this->miniProgram->release($appID);
                    if ($res['errcode'] != 0 || strtolower($res['errmsg']) != 'ok') {
                        if ($retryCount <= 0) {
                            Log::get()->info(sprintf("发布失败：%s", json_encode($res)));
                            return false;
                        }
                        $retryCount--;
                        goto retry;
                    }
                    Log::get()->info(sprintf("发布成功：%s", json_encode($res)));
                    return true;
                } catch (\Throwable $e) {
                    Log::get()->error($e->getTraceAsString());
                }
                break;
            case 'weapp_audit_fail':
            case 'weapp_audit_delay':
                /** @var Cooperative $cooperative */
                $cooperative = $this->cooperativeDao->first(['wx_mp_appid', $appID]);
                $message = sprintf('审核结果：%s - %s', $data['Reason'], date('Y-m-d H:i:s', $data['CreateTime']));
                $cooperative->wx_mp_audit_message = $message;
                $cooperative->save();
                return true;
                break;
        }
        return false;
    }
}